var express = require('express');
var router = express.Router();
var User= require('../models/user.js');
var Comment= require('../models/comment.js');

router.get('/', function(req, res, next){
	res.render('api', { title: 'API Documentation' });
})
//查询你是不是点过赞
router.get('/select_user_number', function(req, res, next){
  var newComment=new Comment({
    img_name:'',
    comment_value:''
  });
  // req.query.img_name
  newComment.getUserByUsernum(req.query.img_name,function(err,results){
    var num='';
    if (results.length> 0) {
      // console.log(results.length);
      num=results;
    }else{
      num=[];
      // console.log(results);
    }
  res.send({ 
    'num': num
  })
  res.end();
  });
})
//查询点过多少赞
router.get('/select_user_all_number', function(req, res, next){
  var newComment=new Comment({
    img_name:'',
    comment_value:''
  });
  // req.query.img_name
  newComment.getUserByUserallnum('13162533772/66961934.859864414.png',function(err,results){
      // console.log(results);
    res.send(results);
    res.end();
  });
});
router.get('/select_moneyuser_phonenumber', function(req, res, next){
  var newComment=new Comment({
    img_name:'',
    comment_value:''
  });
  // req.query.img_name
  console.log(req.query.user_name);
  //用域名查所有需要的数据
  newComment.getUser_admin_phone(req.query.user_name,function(err,results){
    var num='';
    if (results.length> 0) {
      // console.log(results.length);
      num=results;
    }else{
      num=[];
      // console.log(results);
    }
  res.send({ 
    'num': num
  })
  res.end();
  });
})
router.get('/add_comment', function(req, res, next){
  console.log(req.query);
  var newComment=new Comment({
    img_name:req.query.img_name,
    comment_value:req.query.comment_value
  });
  newComment.save(function(err){
    if(err){
      req.flash('error',err);
    }
    console.log("保存成功");
    res.send({ 
      'telephone': 'activeSession',
      'message':'qr_img'
     })
    res.end();
  });
})
var activeSession;
router.get('/sessionstart', function(req, res, next) {
  // console.log(req.params.telephone+"1");
  // console.log(req.body.telephone+'2');
  // console.log(req.query.telephone+'3');
  // console.log(req.query.admin_Name+'3');
  activeSession=req.query.telephone;
  var newUser=new User({
    first_name:req.query.admin_Name,
    phone_number:req.query.telephone,
    company_name:''
  });
  var qr_img=req.query.message;
  //查询是否已经添加
  newUser.getUserByUserName(req.query.admin_Name,req.query.telephone,function(err,results){
    if (results.length> 0) {
      res.send({ 
        'telephone': activeSession,
        'message':qr_img
       })
      res.end();
    }else{
        //添加
      newUser.save(function(err){
        if(err){
          req.flash('error',err);
        }
        console.log("保存成功");
        res.send({ 
          'telephone': activeSession,
          'message':qr_img
         })
      });
      res.end;
    }
  });
})
router.get('/sessionstart_ask', function(req, res, next) {
  res.send({ 
    'telephone': activeSession
   })
})
router.post('/delect_img', function(req, res, next) {
  var src=req.body.data;
  fs.unlink('./public/images/gallery/'+src,function(){
    res.send({'back':'ok'}); 
  });
});
router.post('/add_wx_img', function(req, res, next) {
  // console.log(req.params.telephone+"1");
  // console.log(req.body.telephone+'2');
  // console.log(req.param, req.query, req.body);
  // console.log("服务器端接受到数据:%j",req.param.img);
  // console.log("服务器端接受到数据:%j",req.query.img);
  // console.log("服务器端接受到数据:%j",req.body.img);
  // console.log("服务器端接受到数据:%j",req.body.data);
  var src=req.body.data;
  // var src="";
  var url_weichat=src.replace(/^data:image\/\w+;base64,/, "");
  dataBuffer = new Buffer(url_weichat, 'base64');
  fs.writeFile('./public/images/wx.png', dataBuffer, function(err) {
    if(err){
      console.log('失败');
    }else{
      console.log('成功');
    }
    res.send({'fei':'ok'}); 
  });
})
router.post('/add_img', function(req, res, next) {
  // console.log(req.params.telephone+"1");
  // console.log(req.body.telephone+'2');
  // console.log(req.param, req.query, req.body);
  // console.log("服务器端接受到数据:%j",req.param.img);
  // console.log("服务器端接受到数据:%j",req.query.img);
  // console.log("服务器端接受到数据:%j",req.body.img);
  // console.log("服务器端接受到数据:%j",req.body.data);
  var src=req.body.data;
  // var src="";
  var url_weichat=src.replace(/^data:image\/\w+;base64,/, "");
  dataBuffer = new Buffer(url_weichat, 'base64');
  fs.writeFile('out'+'.png', dataBuffer, function(err) {
    if(err){
      console.log('失败');
    }else{
      console.log('成功');
      // fs.rename('/Users/leyi/workspace/wevent/green_api/out.png','/Users/leyi/workspace/wevent/green_api/public/images/uploads/out.png', function(err){
      fs.rename('./out.png','./public/images/uploads/out.png', function(err){
       if(err){
        throw err;
       }
        console.log('done!');
        res.send({'fei':'ok'}); 
      });
    }
  });

})
router.post('/select_name', function(req, res, next) {
  var image_datas=req.body.data['number_s'];
  var lin_now=req.body.data['lin'];
  console.log(image_datas);
  console.log(lin_now)
  var c=[];
  var inde=0;
  function as(){
    // console.log(image_datas[inde]);
    fs.exists('./public/images/gallery/'+image_datas[inde], function(exists) {
      // console.log('总共进来了几次');
      var a=[];
      if (inde >image_datas.length-1) {
        // console.log('出来了');
        // console.log(c);
        res.send({'names':c});
        return false;
      };
      if (exists) {
        // console.log('有个文件夹');
        var files=fs.readdirSync('./public/images/gallery/'+image_datas[inde]);
        // console.log(files.length);
        if (files.length>0) {
          for (var i=0; i<files.length; i++) {
            if (files[i].indexOf('.D')<0) {
              if (files[i].indexOf(lin_now+'_')==-1) {
                // console.log('消失了');
              }else{
                // console.log('添加了');
                a.push(image_datas[inde]+'/'+files[i]);
                // console.log(a+'1');
              }
            }
          };
          inde=inde+1;
          c=c.concat(a);
          as();
        }else{
          inde=inde+1;
          c=c;
          as();
        }
      }else{
        // res.send({'names':c});
        // console.log(5);
        inde=inde+1;
        as();
      };
    });
  }
  as();
  // console.log(req.body.data[0]);
});
router.post('/select_digital_name', function(req, res, next) {
  function as(){
    var files=fs.readdirSync('./public/images/digital/'+req.body.data);
    var a=[];
    for (var i=0; i<files.length; i++) {
      if (files[i].indexOf('.D')<0) {
        a.push(files[i]);
      }
    };
    return a;
  }
  var c=as();
  // console.log(c);
  // console.log(as()); 
  res.send({'names':c});
});
// var project_name='';
// router.get('/add_progect_name', function(req, res, next) {
//   project_name=req.query.project_name;
//   res.send({'project_name':project_name});
// });
router.post('/add_folder', function(req, res, next) {
  // console.log('123');

  // console.log("服务器端接受到数据:%j",req.body.data);
  var name_image=req.body.data['lin'];
  // var src=req.body.data;
  var src=req.body.data['url'];
  // var src="";
  var url_weichat=src.replace(/^data:image\/\w+;base64,/, "");
  dataBuffer = new Buffer(url_weichat, 'base64');
  fs.exists('./public/images/gallery/'+activeSession, function(exists) {
    function correct(action,indexs){
      action=action.toString();
      if (action.length<indexs) {
        action='0'+action;
      };
      return action;
    }
    var date = new Date();
    var year = date.getFullYear();
    var month = correct(date.getMonth()+1,2);
    var day = correct(date.getDate(),2);
    var hour = correct(date.getHours(),2);
    var minute = correct(date.getMinutes(),2);
    var second = correct(date.getSeconds(),2);

    var name_img=name_image+'_'+parseInt(year.toString()+month .toString()+day .toString()+hour.toString()+minute.toString()+second.toString());
    if (exists) {
      console.log('有这个文件夹');
      // serve file
      fs.writeFile('./public/images/gallery/'+activeSession+'/'+name_img+'.png', dataBuffer, function(err) {
        if(err){
        }else{
          res.send({'fei':name_img});
        }
      });
    } else {
      console.log('没有这个文件夹');
      // mongodbåå
      fs.mkdir('./public/images/gallery/'+activeSession, 0777, function(err){
       if(err){
        console.log(err);
       }else{
        fs.writeFile('./public/images/gallery/'+activeSession+'/'+name_img+'.png', dataBuffer, function(err) {
          if(err){
          }else{
            res.send({'fei':name_img});
          }
        });
       }
      })
    }
  });
    // res.end();
})
router.post('/add_digital', function(req, res, next) {
  var src=req.body.data;
  var url_weichat=src.replace(/^data:image\/\w+;base64,/, "");
  dataBuffer = new Buffer(url_weichat, 'base64');
  fs.exists('./public/images/digital/'+activeSession, function(exists) {
    function correct(action,indexs){
      action=action.toString();
      if (action.length<indexs) {
        action='0'+action;
      };
      return action;
    }
    var date = new Date();
    var year = date.getFullYear();
    var month = correct(date.getMonth()+1,2);
    var day = correct(date.getDate(),2);
    var hour = correct(date.getHours(),2);
    var minute = correct(date.getMinutes(),2);
    var second = correct(date.getSeconds(),2);

    var name_img=parseInt(year.toString()+month .toString()+day .toString()+hour.toString()+minute.toString()+second.toString());
    if (exists) {
      console.log('有这个文件夹');
      // serve file
      fs.writeFile('./public/images/digital/'+activeSession+'/'+name_img+'.png', dataBuffer, function(err) {
        if(err){
        }else{
          res.send({'fei':name_img});
        }
      });
    } else {
      console.log('没有这个文件夹');
      // mongodbåå
      fs.mkdir('./public/images/digital/'+activeSession, 0777, function(err){
       if(err){
        console.log(err);
       }else{
        fs.writeFile('./public/images/digital/'+activeSession+'/'+name_img+'.png', dataBuffer, function(err) {
          if(err){
          }else{
            res.send({'fei':name_img});
          }
        });
       }
      })
    }
  });
})
router.get('/photo', function(req, res, next) {
	var phoneNumber = req.query.telephone
	res.send({
		'imagePath': 'images/uploads/'+phoneNumber+'.jpg'
	})
})

//function to watch uploads folder 

var chokidar = require('chokidar');
var fs = require('fs');

var watcher = chokidar.watch('public/images/uploads/', {ignored: /^\./, persistent: true});

watcher
  .on('add', function(path) {
    console.log('File', path, 'has been added');
    console.log(activeSession);
    if(activeSession){
  		fs.rename(path, 'public/images/uploads/' + activeSession + '.jpg')
  	    //fs.rename(path, 'public/images/uploads/anon/' + Math.random() * 100000000 + '.jpg')
  	} else {
  	    console.log('no user checked in');
  	}
    //var pathMod = path.substring(6);
    //uploadedImages.push(pathMod);
  })
  .on('change', function(path) {
    console.log('File', path, 'has been changed');
  })
  .on('unlink', function(path) {
    console.log('File', path, 'has been removed');
    var pathMod = path.substring(6);
    helperRemoveImage(pathMod);
  })
  .on('error', function(error) {
    console.error('Error occurred', error);
  })

var uploadedImages = [];

var helperRemoveImage = function(target){
  var index = uploadedImages.indexOf(target);
  if( index > -1) {
    uploadedImages.splice(index, 1);
  } 
}

module.exports = router;
